<template>
  <div class="fromEdit">
    <div class="content content1" style="display: none;">
      <p>个人信息</p>
      <div class="item">
        <span></span>
        <div class="userInfo">
          <p>刘德华</p>
          <p>香港TVP华谊电影公司老总/电影演员</p>
          <p>
            <svg-icon icon-class="time" style="font-size: 16px;color:#ff6a00;" />
            时间：2023-030-03 &nbsp;&nbsp;&nbsp;&nbsp; 
            <svg-icon icon-class="address" style="font-size: 16px;color:#ff6a00;" />
            地点：香港九龙湾</p>
        </div>
      </div>
    </div>
    <div  class="content" >
      <p>内 容</p>
      <!-- 没有流程图的数据 -->
      <el-tabs type="card" v-loading="contentLoading" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="流程参数" name="1">
          <div class="centerContent" v-if="options.length != 0 && sourceBlag">
            <div class="cenOne">
              <el-form :model="blruleForm" :rules="blrules" ref="blruleForm" label-width="150px" class="demo-ruleForm autoFrom">
                <!-- :style="item.type=='textarea'?{width:'100%'}:''" -->
                <el-form-item 
                  v-for="(item, index) in options" 
                  :key="index" 
                  :prop="item.filedName" 
                  :label="item.filedCnName">
                  <!-- {{ isShowObj.liucheng=='y' && (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n')) }} -->
                    <el-select 
                      style="width:90%;"
                      filterable
                      class="el-input"
                      v-if="item.type=='select'||item.type=='selectDic'" 
                      :disabled="isShowObj.liucheng=='y' && 
                      (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                      @change="selectDataSetVal(item,item.children.options,blruleForm[item.filedName])"
                      v-model="blruleForm[item.filedName]" clearable placeholder="请选择">
                        <el-option
                          v-for="item in item.children.options"
                          :key="item.optionName"
                          :label="item.optionName"
                          :value="item.optionName">
                        </el-option>
                      </el-select>
                    <el-select 
                    class="el-input"
                    filterable
                    style="width:90%;"
                    v-else-if="item.type=='sql'" 
                    :disabled="isShowObj.liucheng=='y' && 
                    (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                    @change="selectDataSetVal(item,item.children.options,blruleForm[item.filedName])"
                    v-model="blruleForm[item.filedName]" clearable placeholder="请选择">
                      <el-option
                      style="width:90%;"
                        v-for="(sitem,index) in item.children.options"
                        :key="index"
                        :label="sitem[item.filedName]"
                        :value="sitem[item.filedName]">
                      </el-option>
                    </el-select>

                    <div v-else-if="item.type=='date'">
                      <el-date-picker
                       style="width:90%;"
                       :disabled="isShowObj.liucheng=='y' && 
                      (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                        v-if="item.timeType=='start'"
                        v-model="blruleForm[item.filedName]"
                        type="date"
                        placeholder="选择日期">
                      </el-date-picker>
                      <el-time-picker
                       style="width:90%;"
                       :disabled="isShowObj.liucheng=='y' && 
                      (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                        v-if="item.timeType=='end'"
                        v-model="blruleForm[item.filedName]"
                        :picker-options="{
                          selectableRange: '18:30:00 - 20:30:00'
                        }"
                        placeholder="任意时间点">
                      </el-time-picker>
                      <el-date-picker
                        style="width:90%;"
                        :disabled="isShowObj.liucheng=='y' && 
                        (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                        v-if="item.timeType=='all'"
                        v-model="blruleForm[item.filedName]"
                        type="datetime"
                        placeholder="选择日期时间">
                      </el-date-picker>
                    </div>

                    <el-input v-else-if="item.type=='textarea'"
                    style="width:90%;"
                    type="textarea"
                    :rows="4"
                    :disabled="(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n')||(!item.allowChange)" 
                    v-model="blruleForm[item.filedName]" clearable></el-input> 

                    <el-input style="width:90%;" v-else-if="item.type=='webSession'"
                    :disabled="(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n')||(!item.allowChange)" 
                    v-model="blruleForm[item.filedName]" clearable></el-input>
                    
                    <el-input 
                    style="width:90%;"
                    v-else
                    :disabled="isShowObj.liucheng=='y' && (!item.allowChange||(isShowObj.yijian=='n'&&isShowObj.chuangjian=='n'))" 
                    v-model="blruleForm[item.filedName]" clearable></el-input> 

                    <el-tooltip v-if="item.explain" class="item" effect="dark" :content="item.explain" placement="right">
                      <i style="color:#999;" class="el-icon-question"></i>
                    </el-tooltip>
                  
                </el-form-item>
              </el-form>
            </div>
            <div class="cenOne">
              <div v-for="(item, index) in apiOptions" :key="index">
                <label>{{ item.filedCnName }}：</label>
                <el-input
                  style="width: 52%"
                  v-model="item.external_parameter_value"
                  placeholder=""
                  disabled
                ></el-input>
                <el-button
                  style="width: 18%"
                  size="mini"
                  @click="queryItem(item, index)"
                  >查询</el-button
                >
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane
          :label="tabUserList2[keys].name"
          v-for="(keys, index) in listKey"
          :key="index"
          :name="index + 2"
        >
          <div class="cenOnen" v-if="activeName==`${index+2}`">
            <div 
            v-if="isShowObj.liucheng=='n'||
            (isShowObj.liucheng=='y'&& tabUserList2[keys].allowChange&&isShowObj.yijian=='y')||
            (isShowObj.liucheng=='y'&& isShowObj.yijian!='n'&&isShowObj.chuangjian!='n')" 
            style="text-align: right;">
                <i  @click="insertData(keys)" style="margin:0 30px 10px 0;font-size:22px;cursor: pointer;" class="el-icon-circle-plus-outline"></i>
            </div>
            <div>
              <el-table
              :pagination="true"
              :data="addListPage[keys]"
              border
              class="tableAutoBtn"
              max-height="550"
              :header-cell-style="{ background: '#f2f5f8' }"
            >
            <el-table-column
              label="序号"
              align="center"
              type="index"
              width="50">
            </el-table-column>
              <qttableedit
                v-for="(item, index) in tabUserList2[keys].colum"
                :key="index"
                :header="item"
              ></qttableedit>
              <!-- {{ isShowObj }} -->
              <el-table-column align="center" width="80" prop="" label="操作" 
              v-if="isShowObj.liucheng=='n'||
              (isShowObj.liucheng=='y'&& tabUserList2[keys].allowChange&&isShowObj.yijian=='y')||
              (isShowObj.liucheng=='y'&& isShowObj.yijian!='n'&&isShowObj.chuangjian!='n')" >
                <template slot-scope="scope">
                  <el-popconfirm
                    title="确定删除吗？"
                    icon-color="#f00"
                    @confirm="deleteRow(scope.row,keys,scope.$index)"
                  >
                    <el-button slot="reference" size="mini" type="text"
                      >删除</el-button
                    >
                  </el-popconfirm>
                  <el-button @click="editRowData(scope.row,keys,scope.$index)" size="mini" type="text">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="附件" v-if="fileOptions.length!=0" :name="listKey.length+2">
          <div class="centerContent" v-if="options.length != 0 && sourceBlag">
            <div class="cenOne" v-loading="uploadingImage">
              <el-form :model="fileForm" :rules="fileRules" ref="blruleForm2" label-width="160px" class="demo-ruleForm autoFrom2">
                <el-form-item 
                  v-for="(item, index) in fileOptions" :key="index"
                  :rules="[
                    { required: item.required, message: '请上传附件', trigger: 'blur' },
                  ]"
                  :prop="item.filedName" 
                  :label="item.fileType+'：'">
                 <!-- true 禁 -->
                  <el-upload
                    class="upload-demo"
                    style="position:relative"
                    :disabled="(isShowObj.liucheng=='n'&&!item.allowChange)||
                               (isShowObj.yijian=='y'&&!item.allowChange)||
                               (isShowObj.liucheng=='y'&& isShowObj.yijian=='n'&& isShowObj.chuangjian=='n')
                    "
                    :action="httpUrl+get_branch+'/ht-bpmn/activiti/upload?fileType='+item.fileType"
                    :headers="headers"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-upload="beforeUpload"
                    :before-remove="beforeRemove"
                    :on-success="(v)=>{
                      uploadingImage = false
                      $set(fileObjList,item.fileType,v.data)
                      if(fileListArr.length==0){
                        fileListArr.push({fileType:item.fileType,path:v.data})
                      }else{
                        let flag = false
                        fileListArr.forEach((ptem)=>{
                          if(ptem.fileType == item.fileType){
                            flag = true
                            ptem.path = v.data
                          }
                        })
                        if(!flag){
                          fileListArr.push({fileType:item.fileType,path:v.data})
                        }
                      }
                    }"
                    multiple
                    :limit="1000"
                    :on-exceed="handleExceed"
                    :file-list="fileList"
                  >
                  <el-button 
                  :disabled="(isShowObj.liucheng=='n'&&!item.allowChange)||
                              (isShowObj.yijian=='y'&&!item.allowChange)||
                              (isShowObj.liucheng=='y'&& isShowObj.yijian=='n'&& isShowObj.chuangjian=='n')
                  "
                  class="uploadAutoClass" 
                  size="small" 
                  type="primary">点击上传</el-button>
                  <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
                <!-- :style="{color:!item.allowChange?'#999':'#bcc5ff'}" -->
                <div class="fileNamePar" @click="previewFile(fileObjList[item.fileType],-1)" style="color:#999;cursor: pointer;">
                  <p class="fileName">{{ fileObjList[item.fileType] }}</p>
                  <span title="点击预览" v-if="fileObjList[item.fileType]" style="margin-left:10px;">
                    <svg-icon style="font-size:16px;color:#ff4949;position: relative;top:3px;" icon-class="yl2"/>
                  </span>
                </div>
                <i @click="closeFile(item.fileType)" v-if="
                  (isShowObj.liucheng=='n'||isShowObj.yijian=='y')&&(fileObjList[item.fileType]&&item.allowChange)
                " 
                class="el-icon-delete-solid fileClose" />
                </el-form-item>
              </el-form>
            </div>
          </div>  
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 流程 -->
    <div  class="content" v-if="isShowObj.liucheng=='y'">
      <p>流 程</p>
      <div style="padding:36px 0 0 6px;"><steppage :stepsData="stepOptions" :active="stepOptions.length"></steppage></div>
    </div>

    <!-- api查询 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item
          :label="item.label"
          :prop="item.prop"
          v-for="(item, index) in itemList"
          :key="index"
          :rules="item.rules"
        >
          <el-input
            style="width: 90%"
            v-model="ruleForm[item.prop]"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormQuery('ruleForm')"
            >查 询</el-button
          >
          <el-button @click="clena('ruleForm')">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 输入任务名称 -->
    <el-dialog title="" :close-on-click-modal="false" :visible.sync="rwName" width="25%">
      <el-form label-width="75px">
        <el-form-item
          label="任务名称"
          prop="inputName"
        >
          <el-input
            v-model="inputName"
            placeholder="请输入任务名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div style="text-align: right;"><el-button type="primary" @click="commitUserData">确 定</el-button></div>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    
    <div style="text-align: left;padding: 20px;">
      <el-button
        size="mini"
        type="primary"
        v-if="isShowObj.chuangjian=='y'"
        @click="submitForm('blruleForm')"
        >创建任务</el-button
      >
    
      <el-button v-if="isShowObj.yijian=='y'&&showCommitYJBtn"  type="primary" @click="commitYijian('blruleForm')">提交意见</el-button>
      <el-button
        size="mini"
        v-if="isShowObj.yijian=='y'&&showCommitYJBtn"
        @click="staging"
        >暂存</el-button
      >
      <el-button size="mini" v-if="sourceBlag" @click="resetForm('return')">返回</el-button>
    </div>

    <!-- 修改数据 -->
    <el-dialog
      title="修改"
      :visible.sync="updatedialogVisible"
      :close-on-click-modal="false"
      width="50%"
      :before-close="handleClose">
      <el-form ref="form" class="autoClass" :model="dialogform" label-width="100px">
        <el-form-item  :label="item.title" v-for="(item,index) in dialogformOptions" :key="index">
          <el-input v-model="dialogform[item.key]"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加表数据 -->
    <el-dialog :title="addTableTitle"
      :visible.sync="addTableDataFlag"
      :close-on-click-modal="false"
      width="50%"
      >
      <addtable ref="addtable" v-if="addTableDataFlag" @setTableValList="setTableValList" :tabUserList2="tabUserList2[count]" :formItem="addListObj[count]"></addtable>
    </el-dialog>



<!-- 提交意见 -->
    <el-dialog :close-on-click-modal="false" title="提交意见" width="35%" :visible.sync="dialogTableVisible">
        <el-form class="fromClass" label-width="100px">
          <el-form-item label="是否同意" prop="resource">
            <el-radio-group v-model="resource">
              <el-radio label="同意">同意</el-radio>
              <el-radio label="不同意">不同意</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="意见" prop="textarea">
            <el-input
            type="textarea"
            :rows="5"
            maxlength="1000"
            placeholder="请输入内容"
            v-model="textarea">
          </el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="submitFormIsSue('blruleForm')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
  </div>
</template>
  
<script>
import {externalParamearamById,requestgetResByUrl,activiticompleteTask,
  activititaskHistoryInfo,
  activitidefinition} from '@/api/home_/adminCenter';
import qttableedit from '../components/qt_header_table_noedit'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import request from '@/utils/request';
import qttable from '../components/qt_header_table';
import addtable from './tableform';
import qttableno from '../components/qt_header_table_noedit';
import nativeRequest from '@/mixins/nativeRequest';
import steppage from './step'
export default {
  mixins: [nativeRequest],
  components: { qttable, qttableno,steppage,qttableedit,addtable },
  data() {
    return {
      requestUrl:process.env.NODE_ENV === 'production' ? window.location.origin + '/api' : process.env.VUE_APP_BASE_API+'/api',
      showCommitYJBtn:true,//控制切换历史流程及节点的时候控制
      contentLoading:false,
      uploadingImage:false,
      fileList: [],
      fileObjList:{},
      fileListArr: [],
      httpUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: 'bearer ' + getToken()
      },
      fileForm:{},
      fileRules:{},
      fileOptions:[],
      textarea:"",
      resource:"同意",
      dialogTableVisible:false,
      user_id:JSON.parse(sessionStorage.getItem('userInfo')).user_id,
      fqrId:"",
      dataRowCount:-1,
      count:-1,
      addTableTitle:"",
      addTableDataFlag:false,
      dialogformOptions:[],
      updatedialogVisible:false,
      dialogform:{},
      flowId:"",
      stepOptions:[],
      addListPage:{},
      addListObj:{},//多表的时候，给每个表加数据，不能存在独立的对象中，所以放在一起
      outParamsBindFlag:false,
      sourceBlag:true,
      tabHeadList: [],
      riskList:[],
      rwName: false,
      tabUserList2: [],
      listKey: [],
      activeName: '1',
      ruleForm: {},
      dialogTitle: '',
      itemList: [],
      dialogVisible: false,
      inputName: '',
      selectItemOptions: [],
      apiOptions: [],
      options: [],
      isShowObj:null,
      blrules: {},
      blruleForm:{},
      // blruleFormApi:{},
      paramsData:null
    };
  },
  created() {
        this.paramsData = JSON.parse(this.$route.query.paramsObj)
        this.isShowObj = JSON.parse(this.$route.query.isShowObj) //控制页面显影按钮等
        
        //查询流程图
        if (this.isShowObj.liucheng=='y') {
          // 查表头和流程参数
          this.queryexternalParamearamById(this.paramsData.nodeForm,()=>{
            this.queryDataList(this.paramsData.procinstId) //查询数据
          })
          this.createPrelcObj(this.paramsData.procinstId) //查流程图
        }else{
          this.fqrId = this.user_id
          this.queryexternalParamearamById(this.paramsData.place)
        }
  },
  methods: {
    cellClick(row, column, cell, event){
      console.log(row, column, cell, event)
    },
    staging(){
      let params_ = {
          "procinstId":this.paramsData.procinstId,
            "fqrId": this.fqrId,
            "status":'暂存',
            "suggest":`暂存`,
            "userId":this.user_id,
            "formKey":this.paramsData.nodeForm,
            "param": {
              "data":this.addListPage,
              "param": this.blruleForm,
              "files":this.fileListArr
            }
        }
        activiticompleteTask(params_).then(res=>{
          if(res.code==200){
            this.$message.success('已暂存')
          }else{
              this.$message.error(res.msg)
          }
      })
    },
    refreshParFun(v,index,len){
      if(!v.nodeForm){
        return
      }
      this.showCommitYJBtn = index!=len-1?false:true //说明不是最后一个，要禁止编辑
      
      this.activeName = '1'
      this.contentLoading = true
      this.queryexternalParamearamById(v.nodeForm,()=>{
        this.queryDataList(this.paramsData.procinstId) //查询数据
      })
    },
    previewFile(v,i){
      if(!v||i!=-1){
        return
      }
      request({
        url: '/ht-bpmn/activiti/downloadFileSign?url='+v,
        method: 'post',
        data:{}
      }).then((res) => {
         if(res.code==200){
            window.open(res.data)
         }
      })
    },
    beforeUpload(file){
      this.uploadingImage = true
      // file.size = Number.MAX_VALUE;
      // return file;
    },
    sendRequest(){
      let params_ = {
          "procinstId":this.paramsData.procinstId,
            "fqrId": this.fqrId,
            "status":this.resource,
            "suggest":`[${this.resource}] ${this.textarea}`,//text.length==0?'无意见':this.textarea,
            "userId":this.user_id,
            "formKey":this.paramsData.nodeForm,
            "param": {
              "data":this.addListPage,
              "param": this.blruleForm,
              "files":this.fileListArr
            }
        }
        this.checkQequeistsFun(params_,(params_)=>{
            activiticompleteTask(params_).then(res=>{
              if(res.code==200){
                this.$message.success(res.msg)
                this.$router.go(-1)
                this.dialogTableVisible = false
                this.resource = '同意'
                this.textarea = ''
              }else{
                  this.$message.error(res.msg)
              }
          })
        })
    },
    submitFormIsSue(formName){
      let text1 = this.textarea.trim()
      if(this.resource=='不同意'&& text1.length==0){
          this.$message.error('请填写意见')
          return
      }
      if(this.resource=='不同意'&& text1.length!=0){
          // 直接调接口不用校验
          this.sendRequest()
      }
      if(this.resource=='同意'){
        this.$refs[formName].validate((valid) => {
          if (valid) {
              let requiredLen = this.fileOptions.filter((item,index)=>{
                return item.required
              })
              let flag = true
              requiredLen.forEach((item,index)=>{
                let imagePath = this.fileObjList[item.fileType]
                if(!imagePath){
                  flag = false
                }
              })
              if(!flag){ //文件必填不是0
                this.$message.error('请将带*号附件上传')
              }else{
                this.sendRequest()
              }
            }else{
              this.$message.error('请将流程参数填写完整')
            }
      })
      }
  

      return 
      // 以下是原来的逻辑，以上是改后的逻辑
        let text = this.textarea.trim()
        if(this.resource=='不同意'&& text.length==0){
            this.$message.error('请填写意见')
            return
        }
        let params_ = {
          "procinstId":this.paramsData.procinstId,
            "fqrId": this.fqrId,
            "status":this.resource,
            "suggest":`[${this.resource}] ${this.textarea}`,//text.length==0?'无意见':this.textarea,
            "userId":this.user_id,
            "formKey":this.paramsData.nodeForm,
            "param": {
              "data":this.addListPage,
              "param": this.blruleForm,
              "files":this.fileListArr
            }
        }
        this.checkQequeistsFun(params_,(params_)=>{
            activiticompleteTask(params_).then(res=>{
              if(res.code==200){
                this.dialogTableVisible = false
                this.resource = '同意'
                this.textarea = ''
                this.$message.success(res.msg)
                this.$router.go(-1)
              }else{
                  this.$message.error(res.msg)
              }
          })
        })
    },
    commitYijian(formName){
      this.dialogTableVisible=true



      return //以下是原来的逻辑
      this.$refs[formName].validate((valid) => {
          if (valid) {
              let requiredLen = this.fileOptions.filter((item,index)=>{
                return item.required
              })
              if(requiredLen.length==0){//文件必填项是0
                this.resource = '同意'
                this.textarea = ''
                this.dialogTableVisible=true
              }else{
                let flag = true
                requiredLen.forEach((item,index)=>{
                  let imagePath = this.fileObjList[item.fileType]
                  if(!imagePath){
                    flag = false
                  }
                })
                if(flag){ //文件必填不是0
                  this.resource = '同意'
                  this.textarea = ''
                  this.dialogTableVisible=true
                }else{
                  this.$message.error('请将带*号附件上传')
                }
              }
            }else{
              this.$message.error('请将流程参数填写完整')
            }
      })
    },
    handleRemove(file, fileList) {
      let vList = this.fileListArr.filter((item,index)=>{
        return item.path!=file.response.data
      })
      this.fileListArr = JSON.parse(JSON.stringify(vList))
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    closeFile(type){
      let a = JSON.parse(JSON.stringify(this.fileObjList))
      delete a[type]
      this.fileObjList = JSON.parse(JSON.stringify(a))
      this.fileListArr = this.fileListArr.filter((item)=>{return item.fileType!=type})
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除文件？`)
    },
    selectDataSetVal(strObj,options,val){
      options.forEach((item,index)=>{
        if(item.optionName==val){
          this.$set(this.blruleForm,strObj.children.key,item.optionValue)
        }
      })
    },
   
    queryDataList(v){
      request({
        url: '/ht-bpmn/activiti/getNodeData?processInstanceId='+v,
        method: 'get'
      }).then((res) => {
        this.contentLoading = false
        if (res.code == 200) {
          this.fileObjList = {}
          
          this.fileListArr =[]
          this.fileOptions.forEach((cItem)=>{
            res.data.files.forEach((item)=>{
              if(item.fileType == cItem.fileType){
                this.fileObjList[item.fileType] = item.filePath
                this.fileListArr.push({
                  "fileType": item.fileType,
                  "path": item.filePath
                })
              }
            })
          })

     
          this.fqrId = res.data.fqrId
          let obj = Object.keys(this.blruleForm)
          obj.forEach((item,index)=>{ 
            //只有session类型的有默认值，其他的没有。
            let v = this.blruleForm[item]
            this.blruleForm[item] = v?v:res.data.param[item] //流程参数反显
          })
          this.listKey.forEach((item,index)=>{  //表反显
            this.addListPage[item] = res.data.data[item]
          })
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    queryexternalParamearamById(v,callBack){
       //创建任务
       externalParamearamById(v).then((res) => {
            console.error(res)
            if(callBack)callBack();
            this.options = [];
            this.apiOptions = [];
            let arrLabel = res.data.param; //表单
            // 文件
            this.fileOptions = res.data.files; //文件
            this.tabUserList2 = res.data.column;

            this.riskList = res.data.risk||[]

            this.addListObj = {} //清空每个表的新增数据
            this.listKey = []; //表的属性
            this.listKey = Object.keys(res.data.column);
            this.listKey.forEach((item,index)=>{
              this.$set(this.addListObj,item,[]) //给每个表设置一个属性 
            })
            this.addListPage = JSON.parse(JSON.stringify(this.addListObj))
            if (arrLabel && arrLabel.length > 0) {
              arrLabel.forEach((item, index) => {
                if (item.type == 'api') {
                  this.apiOptions.push(item);
                  // this.blruleFormApi[item.filedName] = ''
                }else {
                  if(item.type=='webSession'){
                    let ujson = JSON.parse(sessionStorage.getItem('userInfo'))
                    this.$set(this.blruleForm,item.filedName,ujson[item.webSessionKey])
                  }else{
                    this.$set(this.blruleForm,item.filedName,'')
                  }
                  
                  if(item.type=='select'){//给下拉框类型一个id默认值
                    this.blruleForm[item.children.key] =""
                  }

                  var verRules = [
                      { required:(this.isShowObj.yijian=='n'&& this.isShowObj.chuangjian=='n')?false:item.required, message:`请${item.type=='select'?'选择':'输入'}${item.filedCnName}`, trigger:'change'}
                    ]
                  this.$set(this.blrules,item.filedName,verRules)
                  this.options.push(item);

                }
              });
              this.options.forEach((item,idnex)=>{
                if(item.type=='sql'){
                  request({
                    url: '/ht-bpmn/request/getSqlTypeData',
                    method: 'post',
                    data:{sql:item.sql}
                  }).then((res) => {
                    if(res.code==200){
                        item.children.options = res.data
                    }
                  })
                }
              })
            }
            for(let i = 0;i<this.listKey.length;i++){
              let kstr = this.listKey[i]
              this.setTableAttr(this.tabUserList2[kstr].colum,kstr)
            }
          });
    },
    // 修改
    editRowData(item,key,rowIndex){
      this.dataRowCount = rowIndex
      this.addTableTitle = this.addTableTitle.replace('新增','修改')
      this.count = key
      this.addTableDataFlag = true
      this.$nextTick(()=>{
        this.$refs.addtable.editChangeVal(item)
      })
    },
    handleClick(x){
      this.addTableTitle = '新增“'+x.label+'”数据'
    },
    //弹窗插入数据调用函数
    setTableValList(v){
       //把页面渲染的表数据先给 对象表
      //count:strKey
       // addListPage:页面渲染的数组
       //addListObj：保存多个表每个表里面的字段
      let lsPageList = JSON.parse(JSON.stringify(this.addListPage)) //页面所有表数据
      let listks = JSON.parse(JSON.stringify(this.addListPage[this.count]||[])) //表数据
      if(this.dataRowCount!=-1){ //修改覆盖原拉力的数据
        this.addListObj[this.count].forEach((item,index)=>{
          listks[this.dataRowCount][item.key] = v[item.key]
        })
        this.dataRowCount = -1
      }else{ //新增插入数据
        let obj = {}
        this.addListObj[this.count].forEach((item,index)=>{
          obj[item.key] = v[item.key]
        })
        listks.push(obj)
      }
      lsPageList[this.count] = JSON.parse(JSON.stringify(listks)) 
      this.addListPage = JSON.parse(JSON.stringify(lsPageList))
      this.addTableDataFlag = false //关闭弹窗
    },
    insertData(k) {
      this.count = k
      this.addTableDataFlag = true
    },
    setTableAttr(itemObj,kname){
      itemObj.forEach((item,index)=>{
        if(item.children&&item.children.length>0){
          this.setTableAttr(item.children,kname)
        }else{
          this.addListObj[kname].push({
            key:item.jsonKey,
            name:item.jsonValue,
            required:item.required
          })
        }
      })
    },
    getTitleKeys(v,list){
      list.forEach((item,index)=>{
        if(!item.children || item.children.length==0){
          v.push({
            key:item.jsonKey,
            title:item.jsonValue
          })
        }else{
          this.getTitleKeys(v,item.children)
        }
      })
    },
    getRowClick(row){
      this.flowId = row.flowId
      let a = []
      this.dialogform = {}
      this.getTitleKeys(a,this.tabUserList2)
      setTimeout(()=>{
        a.forEach((item,index)=>{
          this.$set(this.dialogform,item.key,row[item.key])
        })
        this.dialogformOptions = JSON.parse(JSON.stringify(a))
        this.updatedialogVisible = true
      },300)
    },
    getRowClass({ rowIndex, columnIndex }) {
        if (rowIndex == 0) {
            return 'background:#f2f5f8;fontSize:14px;color:#515a6e;'
        }
    },
    createPrelcObj(v){//查流程
        activititaskHistoryInfo({
          "procinstId": v,
        }).then(res=>{
          this.stepOptions = res.data.historyTaskList
        })
      },

    deleteRow(row,key,index){
        let lcLiionstr = JSON.parse(JSON.stringify(this.addListPage[key]))
        lcLiionstr.splice(index,1)
        this.$set(this.addListPage,key,JSON.parse(JSON.stringify(lcLiionstr)))
    },
    submitFormQuery(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          requestgetResByUrl({
            requestBody: this.ruleForm,
            resultPath: this.selectItemOptions.external_parameter_data,
            requestMethod:this.selectItemOptions.external_parameter_requestMethod,
            defaultValue: this.selectItemOptions.external_parameter_value,
            url: this.selectItemOptions.external_parameter_url
          }).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.apiOptions[this.itemIndex].external_parameter_value =
                res.data ? res.data.data : '';
            }
          });
        } else {
          return false;
        }
      });
    },
    clena(formName) {
      this.itemList = [];
      this.ruleForm = {};
      this.dialogVisible = false;
    },
    queryItem(v, i) {
      this.itemIndex = i;
      this.selectItemOptions = JSON.parse(JSON.stringify(v));
      this.rules = {};
      this.itemList = [];
      let vexternal_parameter_requestBody = JSON.parse(
        v.external_parameter_requestBody
      );
      vexternal_parameter_requestBody.forEach((item, index) => {
        this.$set(this.ruleForm, item.filedName, '');
        this.itemList.push({
          label: item.filedCnName,
          prop: item.filedName,
          rules: [
            {
              required: item.required,
              message: '请输入' + item.filedCnName,
              trigger: 'change'
            }
          ]
        });
      });
      this.dialogVisible = true;
    },
    getValByPath(index, keys, obj) {
      if (index == keys.length - 1) {
        return obj[keys[index]];
      }
      return this.getValByPath(index+1, keys, obj[keys[index]]);
    },
    checkQequeistsFun(v,callback){
      let param = []
      let obj = {}

      let flagList = this.riskList.filter((item,index)=>{
        return item.enable==true 
      })
      if(flagList.length==0){
        callback(v)
        return 
      }
      flagList.forEach((item,index)=>{
        obj.riskType = item.riskType
        obj.sqlParams = {}
        item.param.forEach((citem,cindex)=>{
          if(citem.type=='param'){
            let jsonPath = citem.value||''
            let arr = jsonPath.split('.')
            obj.sqlParams[citem.key] = this.getValByPath(0,arr,v)||''
          }else{
            obj.sqlParams[citem.key] = citem.value
          }
        })
        param.push(
          axios.post(
            this.requestUrl+'/ht-bpmn/risk/riskCheck',obj,
            { 
              headers: { 'Authorization': 'bearer '+getToken() }
            }
          )
        )
      })
      Promise.all(param).then(responses => { 
        let errMsg = ''
        let newsArr = responses.filter((item,index)=>{
            if(!item.data.data){
              errMsg = item.data.msg
            }
            return item.data.data == true
        })
        newsArr.length == param.length?callback(v):this.$message.error(errMsg)
      }).catch(error => {
        this.$message.error('校验错误')
      });
      
    },
   
    commitUserData() {
        if(!this.inputName||this.inputName.length==0){
          this.$message.error('请输入任务名称')
          return 
        }

        let params_ = {
            "definitionKey": this.paramsData.definitionKey,
            "matterName":this.inputName,
            "fqrId":this.fqrId,
            "userId":this.user_id,
            "formKey":this.paramsData.place,
            "data": this.addListPage,
            "param":this.blruleForm,
            "files":this.fileListArr
        }
        this.checkQequeistsFun(params_,(params_)=>{
          activitidefinition(params_).then(res=>{
          if(res.code==200){
            this.resetForm()
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
        }) 
        })
    },
  
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            let requiredLen = this.fileOptions.filter((item,index)=>{
              return item.required
            })
            
            let flag = true
            requiredLen.forEach((item,index)=>{
              let imagePath = this.fileObjList[item.fileType]
              if(!imagePath){
                flag = false
              }
            })
            if(!flag){ //文件必填不是0
              this.$message.error('请将带*号附件上传')
              return
            }

            // if(requiredLen.length!=this.fileListArr.length){
            //   this.$message.error('请将带*号附件上传')
            // }else{
              this.rwName = true;
            // }
          } else {
            if(this.activeName!='1'){
              this.$message.error('请把“流程参数”信息填写完整')
            }
            return false;
          }
        });
    },
    resetForm() {
      this.$router.go(-1);
    }
  }
};
</script>
  
<style lang="scss" scoped>
.el-form-item__content{
  position: relative;
}
.fileNamePar{
  width:300px;
  display: flex;
  flex-direction: row;
  position: absolute;
  left: 90px;
  top: 0px;
}
p.fileName{
  max-width:270px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
i.fileClose{
  position: absolute;
  left:400px;
  top: 10px;
  color: #bcc5ff;
  cursor: pointer;
}
i.fileClose:hover{
  color: #ff0000;
}
>>>.el-upload-list{
  display: none;
}
>>>.el-upload-list{
    position:absolute !important;
    left:100px !important;
    top:-6px !important;
}
// >>>.el-upload-list__item-name{
//   width: 220px;
// }
.autoFrom{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
  .el-form-item{
    width: 33%;
  }
}
.autoFrom2{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
  // justify-content: space-between;
  .el-form-item{
    width:40%;
  }
}
.fromEdit {
  padding: 20px 0;
  .content{
    padding: 20px;
    border-bottom:2px solid #f2f5f8;
    >p{
      padding-left: 5px;
      border-left:5px solid #2778bd;
      font-weight: bold;
      margin-bottom: 20px;
      font-size: 15px;
    }
  }
  .content1{
    min-height:160px;
    .item{
      display: flex;
      flex-direction: row;
      span{
        width:80px;
        height: 80px;
        background:rgb(219, 219, 219);
        border-radius: 100%;
      }
    }
    .userInfo{
      margin-left: 20px;
      p{
        line-height: 25px;
        font-size: 14px;
        letter-spacing:1px;
      }
      p:nth-child(1){
        font-size: 16px;
        font-weight: bold;
        color: #2778bd;
      }
      p:nth-child(3){
        color: #999;
        font-size: 10px;
      }
    }
  }
}
.cenOne {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  > p,
  > div {
    width: 33%;
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
    label {
      display: inline-block;
      width: 22%;
      text-align: right;
      font-weight: normal;
      line-height: 33px;
    }
  }
}
.cenOnen{ 
  
}
.centerContent {
  min-height: 20px;
  margin: 10px 0;

  .cenTwo {
    margin-bottom: 10px;
    > div {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      margin-bottom: 10px;
      margin-top: 10px;
      .el-input {
        width: 10%;
      }
      > p {
        margin-bottom: 10px;
        margin-top: 10px;
      }
      label {
        display: inline-block;
        width: 120px;
        text-align: right;
        line-height: 33px;
      }
    }
  }
}
</style>